import React, { useState, useRef } from 'react';
import {
  View,
  StyleSheet,
  Text,
  TouchableOpacity,
  Image,
  ScrollView,
  SafeAreaView,
  TextInput,
  FlatList,
  Dimensions,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { RootStackParamList } from '../../navigation/types';

// 定义搜索结果类型
interface BookItem {
  title: string;
  publisher: string;
  type: string;
}

interface MaterialItem {
  title: string;
  views: string;
  downloads: string;
}

interface CourseItem {
  title: string;
  instructor: string;
  duration: string;
}

interface QuizItem {
  title: string;
  difficulty: string;
  questions: string;
}

interface SearchResults {
  教材: BookItem[];
  资料: MaterialItem[];
  网课: CourseItem[];
  题库: QuizItem[];
  [key: string]: BookItem[] | MaterialItem[] | CourseItem[] | QuizItem[];
}

const Searcher = () => {
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const [activeTab, setActiveTab] = useState('全部');
  const horizontalScrollRef = useRef<ScrollView>(null);
  const contentScrollRef = useRef<ScrollView>(null);
  const screenWidth = Dimensions.get('window').width;
  
  // 模拟搜索结果数据
  const searchResults: SearchResults = {
    "教材": [
      { title: "有机化学 第5版", publisher: "高等教育出版社", type: "数学" },
      { title: "有机化学(第六版)", publisher: "高等教育出版社", type: "数学" },
      { title: "有机化学 上册 (第六版)", publisher: "高等教育出版社", type: "数学" },
    ],
    "资料": [
      { title: "有机化学题库", views: "12565", downloads: "1016" },
      { title: "有机化学练习题", views: "8234", downloads: "782" },
      { title: "有机化学实验指导", views: "6521", downloads: "543" },
    ],
    "网课": [
      { title: "北京大学《有机化学》2022-2023学年", instructor: "王教授", duration: "48课时" },
      { title: "清华大学《有机化学基础》2021-2022学年", instructor: "李教授", duration: "36课时" },
    ],
    "题库": [
      { title: "有机化学选择题100题", difficulty: "中等", questions: "100题" },
      { title: "有机化学考研真题", difficulty: "困难", questions: "200题" },
    ]
  };

  // 导航选项卡
  const tabOptions = ['全部', '教材', '资料', '网课', '题库'];

  // 处理内容区域滑动事件
  const handleContentScroll = (event: any) => {
    const offsetX = event.nativeEvent.contentOffset.x;
    const page = Math.round(offsetX / screenWidth);
    if (page >= 0 && page < tabOptions.length) {
      setActiveTab(tabOptions[page]);
      // 同步导航栏滚动位置
      horizontalScrollRef.current?.scrollTo({
        x: page * 80, // 估计每个选项卡的宽度
        animated: true
      });
    }
  };

  // 切换选项卡时滚动到对应内容区域
  const switchTab = (tab: string, index: number) => {
    setActiveTab(tab);
    contentScrollRef.current?.scrollTo({
      x: index * screenWidth,
      animated: true
    });
  };

  const renderAllContent = () => {
    return (
      <ScrollView
        ref={contentScrollRef}
        horizontal
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        onMomentumScrollEnd={handleContentScroll}
      >
        {/* 全部 */}
        <View style={[styles.pageContent, { width: screenWidth }]}>
          <ScrollView>
            {renderSection('教材', searchResults.教材)}
            {renderSection('资料', searchResults.资料)}
            {renderSection('网课', searchResults.网课)}
            {renderSection('题库', searchResults.题库)}
          </ScrollView>
        </View>
        
        {/* 教材 */}
        <View style={[styles.pageContent, { width: screenWidth }]}>
          <ScrollView>
            {renderSection('教材', searchResults.教材)}
          </ScrollView>
        </View>
        
        {/* 资料 */}
        <View style={[styles.pageContent, { width: screenWidth }]}>
          <ScrollView>
            {renderSection('资料', searchResults.资料)}
          </ScrollView>
        </View>
        
        {/* 网课 */}
        <View style={[styles.pageContent, { width: screenWidth }]}>
          <ScrollView>
            {renderSection('网课', searchResults.网课)}
          </ScrollView>
        </View>
        
        {/* 题库 */}
        <View style={[styles.pageContent, { width: screenWidth }]}>
          <ScrollView>
            {renderSection('题库', searchResults.题库)}
          </ScrollView>
        </View>
      </ScrollView>
    );
  };

  const renderSection = (title: string, items: any[]) => {
    if (!items || items.length === 0) return null;
    
    return (
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>{title}</Text>
        {items.map((item, index) => (
          <TouchableOpacity key={index} style={styles.resultItem}>
            {title === '教材' && (
              <View style={styles.bookItem}>
                <View style={styles.bookCover}></View>
                <View style={styles.bookInfo}>
                  <Text style={styles.itemTitle}>{item.title}</Text>
                  <Text style={styles.publisher}>{item.publisher}</Text>
                  <View style={styles.tagContainer}>
                    <Text style={styles.tag}>{item.type}</Text>
                  </View>
                </View>
              </View>
            )}
            
            {title === '资料' && (
              <View style={styles.materialItem}>
                <Text style={styles.itemTitle}>{item.title}</Text>
                <View style={styles.statsContainer}>
                  <Text style={styles.stats}>👁 {item.views}</Text>
                  <Text style={styles.stats}>⬇️ {item.downloads}</Text>
                </View>
              </View>
            )}
            
            {title === '网课' && (
              <View style={styles.courseItem}>
                <Text style={styles.itemTitle}>{item.title}</Text>
                <Text style={styles.courseInfo}>{item.instructor} | {item.duration}</Text>
              </View>
            )}
            
            {title === '题库' && (
              <View style={styles.quizItem}>
                <Text style={styles.itemTitle}>{item.title}</Text>
                <Text style={styles.quizInfo}>难度: {item.difficulty} | {item.questions}</Text>
              </View>
            )}
          </TouchableOpacity>
        ))}
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <Text style={styles.backButton}>{'<'}</Text>
        </TouchableOpacity>
        <View style={styles.searchBar}>
          <TextInput
            style={styles.input}
            value=''
            editable={false}
          />
        </View>
        <TouchableOpacity>
          <Text style={styles.searchButton}>搜索</Text>
        </TouchableOpacity>
      </View>
      
      <View style={styles.tabContainer}>
        <ScrollView 
          ref={horizontalScrollRef}
          horizontal 
          showsHorizontalScrollIndicator={false}
        >
          {tabOptions.map((tab, index) => (
            <TouchableOpacity 
              key={index}
              style={[styles.tab, activeTab === tab && styles.activeTab]}
              onPress={() => switchTab(tab, index)}
            >
              <Text style={[styles.tabText, activeTab === tab && styles.activeTabText]}>{tab}</Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>
      
      {renderAllContent()}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    marginTop: 20,
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 15,
    paddingVertical: 10,
    backgroundColor: '#fff',
  },
  backButton: {
    fontSize: 24,
    marginRight: 10,
  },
  searchBar: {
    flex: 1,
    backgroundColor: '#f0f0f0',
    borderRadius: 20,
    paddingHorizontal: 15,
    height: 40,
    justifyContent: 'center',
  },
  input: {
    fontSize: 14,
  },
  searchButton: {
    marginLeft: 15,
    fontSize: 16,
  },
  tabContainer: {
    backgroundColor: '#fff',
    paddingVertical: 10,
  },
  tab: {
    paddingHorizontal: 20,
    paddingVertical: 8,
    marginHorizontal: 5,
  },
  activeTab: {
    borderBottomWidth: 2,
    borderBottomColor: '#4A90E2',
  },
  tabText: {
    fontSize: 16,
    color: '#666',
  },
  activeTabText: {
    color: '#4A90E2',
    fontWeight: 'bold',
  },
  content: {
    flex: 1,
    padding: 15,
  },
  section: {
    marginBottom: 20,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  resultItem: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 15,
    marginBottom: 10,
  },
  itemTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 5,
  },
  bookItem: {
    flexDirection: 'row',
  },
  bookCover: {
    width: 60,
    height: 80,
    backgroundColor: '#e0e0e0',
    marginRight: 15,
    borderRadius: 4,
  },
  bookInfo: {
    flex: 1,
  },
  publisher: {
    color: '#888',
    marginBottom: 8,
  },
  tagContainer: {
    flexDirection: 'row',
  },
  tag: {
    backgroundColor: '#f0f0f0',
    paddingHorizontal: 10,
    paddingVertical: 2,
    borderRadius: 12,
    fontSize: 12,
  },
  materialItem: {
    
  },
  statsContainer: {
    flexDirection: 'row',
    marginTop: 5,
  },
  stats: {
    color: '#888',
    marginRight: 15,
    fontSize: 14,
  },
  courseItem: {
    
  },
  courseInfo: {
    color: '#888',
  },
  quizItem: {
    
  },
  quizInfo: {
    color: '#888',
  },
  pageContent: {
    padding: 15,
  },
});

export default Searcher;
